package com.sc.interceptor;

import com.sc.pojo.Menu;
import com.sc.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().contains("/to")) return true;
        if (request.getRequestURI().contains("/check")) return true;
        User u = (User) request.getSession().getAttribute("theUser");
        if (u==null){response.sendRedirect(request.getContextPath()+"/toLogin");return false;}
        if (u.getR() == null || u.getR().getMenus() == null) {
            request.getRequestDispatcher("/WEB-INF/admin/nomenu.jsp").forward(request,response);
            return false;
        }
        List<Menu> list = u.getR().getMenus();
        String URI = request.getRequestURI();
        URI = URI.substring(request.getContextPath().length());
        for (Menu m:list){
            if (URI.equals(m.getUrl())){
                return true;
            }
        }
        request.getRequestDispatcher("/WEB-INF/admin/nomenu.jsp").forward(request,response);
        return false;
    }
}
